package com.bytenebula.asteroid.controller;

import com.bytenebula.asteroid.ByteNebulaException;
import com.bytenebula.asteroid.ResponseResult;
import com.bytenebula.asteroid.ResultCodes;
import com.bytenebula.asteroid.ddl.SqlBuilder;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.row.Db;
import com.zaxxer.hikari.HikariDataSource;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.log4j.Log4j2;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.bytenebula.asteroid.entity.MetaTable;
import com.bytenebula.asteroid.service.MetaTableService;

import java.util.List;

/**
 *  控制层。
 *
 * @author patrick
 * @since 2024-09-15
 */
@Tag(name = "Metadata Table Service")
@RestController
@RequestMapping("/meta/table")
@ResponseResult
@Log4j2
public class MetaTableController {

    @Autowired
    private MetaTableService metaTableService;

    @Autowired
    private SqlBuilder sqlBuilder;

    @Autowired
    private JdbcTemplate template;

    /**
     * 添加数据表和字段列表
     *
     * @param table
     * @return 添加成功返回新数据表Id，否则返回NULL
     */
    @PostMapping("save")
    public Integer save(@RequestBody MetaTable table) {
        table.setId(null);
        table.setTenantId(1);
        table.setCreateUserId(1);
        table.setLastModifiedUserId(1);

        try {
            Integer newTableId = metaTableService.saveWithColumns(table);
            if (newTableId == null) {
                throw new ByteNebulaException(ResultCodes.CREATE_TABLE_FAILED, table.getTableName());
            }

            String sql = sqlBuilder.generateCreateTableDll(table);
            template.execute(sql);

            return newTableId;
        } catch (Exception e) {
//            log.fatal(ResultCodes.DB_OPERATION_FAILED);
//            log.fatal(e.getMessage());
//            log.fatal(e.getCause());
            throw new ByteNebulaException(ResultCodes.DB_OPERATION_FAILED, e);
        }
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public boolean remove(@PathVariable Integer id) {
        return metaTableService.removeById(id);
    }

    /**
     * 根据主键更新。
     *
     * @param metaTable 
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    public boolean update(@RequestBody MetaTable metaTable) {
        return metaTableService.updateById(metaTable);
    }

    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public List<MetaTable> list(boolean withRelation) {
        return metaTableService.list();
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @param withRelation 查询时是否包含关联对象
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public MetaTable getInfo(@PathVariable Integer id, boolean withRelation) {
        if (withRelation)
            return metaTableService.getOneWithRelationsById(id);
        else return metaTableService.getById(id);
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<MetaTable> page(Page<MetaTable> page) {
        return metaTableService.page(page);
    }

}
